package net.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;

import com.sun.net.httpserver.HttpServer;

public class BasicHttpExample {
	protected HttpClientHelper client;
	static final Logger logger = LogManager.getLogger(FileHttpHandlerTest.class.getName());
	protected HttpServer httpServer;
	protected FileHttpHandler fileHttpHandler;
	protected String baseUrl = "http://localhost:8010";

	@Test
	public void testBasicHttpExample() {
		InetSocketAddress addr = new InetSocketAddress(8010);
		try {
			httpServer = HttpServer.create(addr, 0);
		} catch (IOException e) {
			logger.error("", e);
			Assert.fail();
		}
		fileHttpHandler = new FileHttpHandler(".", true);
		httpServer.createContext("/", fileHttpHandler);
		httpServer.setExecutor(Executors.newCachedThreadPool());
		httpServer.start();
		client = new HttpClientHelper();
		String url = baseUrl + "/src/test/resources/dirWithIndex/index.html";
		// create a method object
		HttpMethod method = new GetMethod(url);
		String responseBody = client.queryHttpServer(method);
		Assert.assertEquals(200,method.getStatusCode());
		Assert.assertTrue(responseBody.contains("This is index.html."));
		// clean up the connection resources
		method.releaseConnection();
		httpServer.stop(0);
	}
}
